package handlers

import (
	"context"
	"strconv"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/kitex-examples/bizdemo/easy_note/cmd/api/rpc"
	"github.com/cloudwego/kitex-examples/bizdemo/easy_note/kitex_gen/notedemo"
	"github.com/cloudwego/kitex-examples/bizdemo/easy_note/pkg/constants"
	"github.com/cloudwego/kitex-examples/bizdemo/easy_note/pkg/errno"
	"github.com/hertz-contrib/jwt"
)

// UpdateNote update user info
// 处理了一个http请求
// 作用就是更新note
func UpdateNote(ctx context.Context, c *app.RequestContext) {
	//创建一个映射的实体结构
	var noteVar NoteParam
	//映射body请求参数
	//处理错误
	if err := c.Bind(&noteVar); err != nil {
		SendResponse(c, errno.ConvertErr(err), nil)
		return
	}

	//用户信息获取
	claims := jwt.ExtractClaims(ctx, c)
	userID := int64(claims[constants.IdentityKey].(float64))
	//noteId是通过url参数的形式传递的
	noteIDStr := c.Param(constants.NoteID)
	noteID, err := strconv.ParseInt(noteIDStr, 10, 64)
	//处理错误
	if err != nil {
		SendResponse(c, errno.ConvertErr(err), nil)
		return
	}
	//参数校验
	if noteID <= 0 {
		SendResponse(c, errno.ParamErr, nil)
		return
	}
	//封装rpc请求参数的内容
	req := &notedemo.UpdateNoteRequest{NoteId: noteID, UserId: userID}
	//设置Title
	if len(noteVar.Title) != 0 {
		req.Title = &noteVar.Title
	}
	//设置Content
	if len(noteVar.Content) != 0 {
		req.Content = &noteVar.Content
	}
	//交给rpc请求的client做rpc调用
	//处理错误
	if err = rpc.UpdateNote(context.Background(), req); err != nil {
		SendResponse(c, errno.ConvertErr(err), nil)
		return
	}
	//成功
	SendResponse(c, errno.Success, nil)
}
